//每个格子的宽高
var BLOCK_WIDTH = 32;
var BLOCK_HEIGTH = 36;
//两种方块
var ORANGE_BLOCK_RECT = cc.rect(0, 0, BLOCK_WIDTH, BLOCK_HEIGTH);
var GARY_BLOCK_RECT = cc.rect(BLOCK_WIDTH, 0, BLOCK_WIDTH, BLOCK_HEIGTH);
//行列数
var ROW = 9;
var COL = 9;
//所有方块左下角坐标
var BLOCK_ORIGIN_X = 22;
var BLOCK_ORIGIN_Y = 55;
//方块摆放时的偏移量
var OFFSET_X = 1;
var OFFSET_Y = -7.5;
//奇数行错位
var OFFSET_ODD = 16;
//可触摸矩形半宽、高
var TOUCH_HALF_WIDTH = 16;
var TOUCH_HALF_HEIGTH = 13;
//玩家初始位置
var PLAYER_INIT_ROW = 4;
var PLAYER_INIT_COL = 4
//玩家角色宽高
var PLAYER_WIDTH = 66;
var PLAYER_HEIGTH = 118;
//各种状态
var STATE_PLAY = 0;
var STATE_WIN = 1;
var STATE_FAIL = 2;
var STATE_END = 3;
//各种标记
var PLAYER_TAG = 1;

var MainLayer = cc.Layer.extend({
    blockLayer: null,
    blockArray: null,
    trapped_Animate: null,
    move_Animate: null,
    player: null,
    curPlayerRow: 0,
    curPlayerCol: 0,
    step: 0,
    state: STATE_END,
    resultLayer: null,
    ctor: function () {
        this._super();
        this.init();
    },
    init: function () {
        this._super();

        this.createAnimate();
        this.addBackground();
        this.addHexagon();

        //绑定触摸事件
        cc.eventManager.addListener({
            event: cc.EventListener.TOUCH_ONE_BY_ONE,
            swallowTouches: true,
            onTouchBegan: this.onTouchBegan.bind(this),
            onTouchEnded: this.onTouchEnded.bind(this)
        }, this);
    },
    //获取六边形坐标
    getHexagonPosition: function (row, col) {
        var isOffset = row % 2;
        //计算错位坐标
        var x = col * (BLOCK_WIDTH + OFFSET_X) + OFFSET_ODD * isOffset;
        var y = row * (BLOCK_HEIGTH + OFFSET_Y);
        return cc.p(x + BLOCK_ORIGIN_X, y + BLOCK_ORIGIN_Y);
    },
    //选择六边形
    selectHexagon: function (row, col) {
        var blockPos = this.getHexagonPosition(row, col);
        var blockSprite = new cc.Sprite(res.Block_png, ORANGE_BLOCK_RECT);
        blockSprite.setPosition(blockPos);
        this.blockLayer.addChild(blockSprite);
        this.blockArray[row][col] = true;
    },
    //判断是否点击到六边形中
    isTouchInHexagon: function (touchPos, row, col) {
        var blockPos = this.getHexagonPosition(row, col);
        //检测谁否点击在矩形中
        var minPos = cc.p(blockPos.x - TOUCH_HALF_WIDTH, blockPos.y - TOUCH_HALF_HEIGTH);
        var maxPos = cc.p(blockPos.x + TOUCH_HALF_WIDTH, blockPos.y + TOUCH_HALF_HEIGTH);
        if (touchPos.x < minPos.x) return false;
        if (touchPos.y < minPos.y) return false;
        if (touchPos.x > maxPos.x) return false;
        if (touchPos.y > maxPos.y) return false;
        return true;
    },
    //是否被选中过
    isBeSelected: function (row, col) {
        return this.blockArray[row][col];
    },
    //添加玩家
    addPlayer: function () {
        if(this.player != null){
            this.removeChildByTag(PLAYER_TAG);
        }

        this.player = new cc.Sprite();
        this.player.setPosition(this.getHexagonPosition(PLAYER_INIT_ROW, PLAYER_INIT_COL));
        this.curPlayerRow = PLAYER_INIT_ROW;
        this.curPlayerCol = PLAYER_INIT_COL;
        this.player.setAnchorPoint(0.5, 0.17);
        this.player.runAction(this.move_Animate);
        this.addChild(this.player,2,PLAYER_TAG);
    },
    //创建动画
    createAnimate: function () {
        var texture = cc.textureCache.addImage(res.Player_png);
        var rect = cc.rect(0, 0, PLAYER_WIDTH, PLAYER_HEIGTH);
        var trapped_Frames = new Array();
        for (var i = 0; i < 6; i++) {
            var frame = new cc.SpriteFrame(texture, rect);
            trapped_Frames.push(frame);
            rect.x = rect.x + PLAYER_WIDTH;
        }
        var trapped_Animation = new cc.Animation(trapped_Frames, 0.2);
        this.trapped_Animate = new cc.Animate(trapped_Animation).repeatForever();

        var move_Frames = new Array();
        rect.x = 0;
        rect.y = PLAYER_HEIGTH;
        for (var i = 0; i < 4; i++) {
            var frame = new cc.SpriteFrame(texture, rect);
            move_Frames.push(frame);
            rect.x = rect.x + PLAYER_WIDTH;
        }
        var move_Animation = new cc.Animation(move_Frames, 0.2);
        this.move_Animate = new cc.Animate(move_Animation).repeatForever();
    },
    //添加六边形
    addHexagon: function () {
        //记录六边形的数组,记录是否被点过
        this.blockArray = new Array();
        for (var i = 0; i < ROW; i++) {
            this.blockArray[i] = new Array();
            for (var j = 0; j < COL; j++) {
                this.blockArray[i][j] = false;
            }
        }

        //存放橙色六边形的层
        this.blockLayer = new cc.Layer();
        this.blockLayer.setPosition(0, 0);
        this.addChild(this.blockLayer,1);

        //创建六边形
        for (var i = 0; i < ROW; i++) {
            for (var j = 0; j < COL; j++) {
                var blockSprite = new cc.Sprite(res.Block_png, GARY_BLOCK_RECT);
                blockSprite.setPosition(this.getHexagonPosition(i, j));
                this.addChild(blockSprite, 0);
            }
        }
    },
    //添加背景
    addBackground: function () {
        var winSize = cc.Director.sharedDirector.getWinSize();
        var centerPos = cc.p(winSize.width / 2, winSize.height / 2);

        //创建背景图片
        var bgSprite = new cc.Sprite(res.Background_jpg);
        bgSprite.setPosition(centerPos);
        this.addChild(bgSprite);

        var label = new cc.LabelTTF("power by cocos2d-x", 'Times New Roman',20);
        label.setPosition(centerPos.x,centerPos.y/4);
        bgSprite.addChild(label);
    },
    //触摸开始
    onTouchBegan: function (touch, event) {
        return true;
    },
    //触摸结束
    onTouchEnded: function (touch, event) {
        var touchPos = touch.getLocation();
        var isFind = false;
        for (var i = 0; i < ROW; i++) {
            for (var j = 0; j < COL; j++) {
                if (!this.isBeSelected(i, j) && this.isTouchInHexagon(touchPos, i, j)) {
                    this.selectHexagon(i, j);
                    this.movePlayer();
                    isFind = true;
                    break;
                }
            }
            if (isFind) {
                break;
            }
        }
    },
    movePlayer: function () {
        this.step++;
        if (this.state == STATE_WIN) {
            this.changeState(STATE_END);
        }else if (this.state == STATE_FAIL) {
            if(this.moveOneWhenFail() == false){
                this.changeState(STATE_END);
            }
        }else if(this.state == STATE_PLAY){
            var nextPos = getNextByBFS(cc.p(this.curPlayerRow,this.curPlayerCol),this.blockArray);
            if(nextPos == false){
                this.moveOneWhenFail();
                this.changeState(STATE_FAIL);
                return;
            }
            this.curPlayerRow = this.curPlayerRow + nextPos.x;
            this.curPlayerCol = this.curPlayerCol + nextPos.y;
            this.player.setPosition(this.getHexagonPosition(this.curPlayerRow, this.curPlayerCol));

            if (this.curPlayerRow == 0
                || this.curPlayerRow == ROW - 1
                || this.curPlayerCol == 0
                || this.curPlayerCol == COL - 1) {
                this.changeState(STATE_WIN);
            }
        }
    },
    changeState: function(stateNum){
        switch (this.state){
            case STATE_PLAY:
                if(stateNum == STATE_WIN){
                    this.state = STATE_WIN;
                } else if(stateNum == STATE_FAIL){
                    this.player.stopAction(this.move_Animate);
                    this.player.runAction(this.trapped_Animate);
                    this.state = STATE_FAIL;
                }
                break;
            case STATE_WIN:
                if(stateNum == STATE_END){
                    this.resultLayer = new ResultLayer(false);
                    this.addChild(this.resultLayer,3);
                    this.state = STATE_END;
                }
                break;
            case STATE_FAIL:
                if(stateNum == STATE_END){
                    this.resultLayer = new ResultLayer(true);
                    this.addChild(this.resultLayer,3);
                    this.state = STATE_END;
                }
                break;
            case STATE_END:
                if(stateNum == STATE_PLAY){
                    this.resetGame();
                    this.state = STATE_PLAY;
                }
                break;
        }
    },
    ramdonBlock : function(){
        var num = Math.round(cc.random0To1() * 5) + 10;
        for(var i=0;i < num;i++){
            var r = Math.floor(cc.random0To1() * 9);
            var c = Math.floor(cc.random0To1() * 9);
            this.selectHexagon(r,c);
        }
    },
    moveOneWhenFail: function(){
        var i = Math.floor(cc.random0To1() * 6);
        i = i%6;
        for(var index = 0;index < 6;index++){
            var isOdd = this.curPlayerRow % 2;
            var x = this.curPlayerRow + dirVector[i][isOdd].x;
            var y = this.curPlayerCol + dirVector[i][isOdd].y;
            if(this.blockArray[x][y] == false){
                this.curPlayerRow = this.curPlayerRow + dirVector[i][isOdd].x;
                this.curPlayerCol = this.curPlayerCol + dirVector[i][isOdd].y;
                this.player.setPosition(this.getHexagonPosition(this.curPlayerRow, this.curPlayerCol));
                return true;
            }
            i++;
            i = i%6;
        }
        return false;
    },
    resetGame: function () {
        this.blockLayer.removeAllChildren();

        for (var i = 0; i < ROW; i++) {
            for (var j = 0; j < COL; j++) {
                this.blockArray[i][j] = false;
            }
        }

        this.addPlayer();
        this.ramdonBlock();
        this.step = 0;
    }
});